<?php namespace Admin\Controller; 

use Hdphp\Controller\Controller;

//测试控制器
class CategoryController extends CommonController{
	private $cateModel;
	//构造函数
	public function __init()
	{
		parent::__init();
		$this->cateModel = new \Common\Model\Category;
	}
	
    //展示
    public function index(){
//  	获得数据
		$cateData = $this->cateModel->where("pid = 0")->get();
//		对数据进行树状处理
//		$cateData = Data::tree($cateData,'cname','cid','pid');
		View::with('cateData',$cateData);
		$typeModel = new \Common\Model\Type;
		$typeData = $typeModel->get();
		View::with('typeData',$typeData);
       	View::make();
    }
//	展示子分类
	public function showSon(){
//		获得cid
		$cid = Q('get.cid',0,'intval');
//		总子集
		$data = $this->cateModel->get();
		$cids = $this->cateModel->getSon($data,$cid);
		$cids[] = $cid;
//		获得数据
		$cateData = $this->cateModel->where("cid IN(".implode(',', $cids).")")->get();
//		p($cateData);
		$cateData = Data::tree($cateData,'cname','cid','pid');
		View::with('cateData',$cateData);
		$typeModel = new \Common\Model\Type;
		$typeData = $typeModel->get();
		View::with('typeData',$typeData);
		View::make();
	}
	
//	添加
	public function add(){
		if(IS_POST){
			if(!$this->cateModel->store()) View::error($this->cateModel->getError());
			View::success('添加成功',U('index'));
		}
//		类型
		$typeModel = new \Common\Model\Type;
		$typeData = $typeModel->get();
		View::with('typeData',$typeData);
		View::make();
	}
//	添加子类
	public function addSon(){
//		获得提交过来的父类id
		$pid = Q('get.cid');
//		添加提交的内容
		if(IS_POST){
			if(!$this->cateModel->addSon()) View::error($this->cateModel->getError());
			View::success('添加成功！',U('index'));
		}
//		获得父级分类的信息
		$parent = $this->cateModel->where("cid = {$pid}")->find();
//		分配数据
		View::with('parent',$parent);
		
//		类型
		$typeModel = new \Common\Model\Type;
		$typeData = $typeModel->get();
		View::with('typeData',$typeData);
		
		View::make();
	}
	
//	编辑分类
	public function edit(){
//		获得编辑分类ID
		$cid = Q('get.cid',0,'intval');
		if(IS_POST){
			if(!$this->cateModel->edit()) View::error($this->cateModel->getError());
			View::success('修改成功！');
		}
//		获得旧数据
		$oldData = $this->cateModel->where("cid = {$cid}")->find();
		View::with('oldData',$oldData);
		
//		获得分类信息
		$cate = $this->cateModel->getNoMy($cid);
//		分配数据
		View::with('allData',$cate);
		
//		类型
		$typeModel = new \Common\Model\Type;
		$typeData = $typeModel->get();
		View::with('typeData',$typeData);
		
		View::make();
	}
	
//	删除
	public function del(){
//		获得要删除的id
		$cid = Q('get.cid',0,'intval');
//		获得pid
		$pid = $this->cateModel->where("cid = {$cid}")->pluck('pid');
//		将子类的pid上移一位
		$this->cateModel->where("pid = {$cid}")->save(array('pid'=>$pid));
//		删除该分类
		$this->cateModel->where("cid = {$cid}")->delete();
//		成功提示
		View::success('删除成功',U('index'));
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
